<?php defined('SYSPATH') OR die('No direct access allowed.');

abstract class Template_Controller extends Controller {
    public $template = 'view_template';
    public $head = '';
    public $content = '';
    public $title = '';

    // Default to do auto-rendering
    public $auto_render = TRUE;
    public $need_template = true;
    /**
     * Template loading and setup routine.
     */
    public function __construct()
    {
        parent::__construct();

        if ($this->need_template) {
            $this->template = new View($this->template);

            //Segmenting, make program more structured
            $tsegments = array_diff(Router::$rsegments, Router::$arguments);
            if ($tsegments[count($tsegments) - 1] != Router::$method) $tsegments[] = Router::$method;
            $path = implode('/', $tsegments);

            $headpath = "head/".$path;
            $contentpath = "content/".$path;
            
            try
            {
                $this->head = View::factory($headpath);
            }
            catch (Exception $ex)
            {
                $this->head = View::factory('null');
            }
            try
            {
                $this->content = View::factory($contentpath);
            }
            catch (Exception $ex)
            {
                $this->content = View::factory('null');
            }

            if ($this->auto_render == TRUE)
            {
                // Render the template immediately after the controller method
                Event::add('system.post_controller', array($this, '_render')); //$this->_render
            }
        }
    }

    public function _render()
    {
        if ($this->auto_render == TRUE)
        {
            if ($this->need_template){
                $this->template->head = $this->head;
                $this->template->content = $this->content;
                $this->template->title = $this->title;
            }
            
            $this->template->render(TRUE);
        }
    }

    /**
     * Set template
     * @param string $template
     */
    public function set_template($template = NULL)
    {
        if ($template)
        $this->template = $template;
        $this->template = new View($this->template);
        if ($this->auto_render == TRUE)
        {
            Event::add('system.post_controller', array($this, '_render'));
        }
    }
} // End Template_Controller